package com.bit.net;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 请求报文类型枚举
 *
 * @since 2018/10/10
 */
public class EachModulModelMessages {


    private Map<Integer, Class<? extends Message>> messages = new ConcurrentHashMap();


    /**
     * 根据请求{@code code}获取目标请求类型
     *
     * @param code 请求类型码
     * @return 目标请求类型
     */
    public Class getTargetClass(int code) {
        return messages.get(code);
    }

    /**
     * 根据响应报文原类型获取响应
     *
     * @param clazz 响应报文原类型
     */
    public int getTargetCode(Class<? extends Message> clazz) {
        for (Map.Entry<Integer, Class<? extends Message>> integerClassEntry : messages.entrySet()) {
            if (integerClassEntry.getValue().equals(clazz)) {
                return integerClassEntry.getKey();
            }
        }
        throw new IllegalArgumentException("Unsupported class of " + clazz);
    }


    /**
     * 注册新消息
     *
     * @param code
     * @param messageClass
     */
    public void registerMessage(int code, Class<? extends Message> messageClass) {
        Class clazz = messages.putIfAbsent(code, messageClass);
        if (clazz != null) {
            throw new IllegalArgumentException("message code " + code + " has bean registered");
        }
    }


}
